<?php

class UsersController extends AppController {

    var $name = 'Users';
    var $helpers = array('Html', 'Form');
    var $paginationLimit='10';
    
    function beforeFilter() {
        $this->set('page_title', 'User Management');
        parent::beforeFilter();
        $this->Auth->fields = array(
            'username' => 'email',
            'password' => 'password'
        );
        if (isset($this->params['admin'])) {
            $this->Auth->userScope = array('User.is_admin' => 'Y');
            $this->Auth->loginAction = array('admin' => true, 'controller' => 'users', 'action' => 'login');
            $this->Auth->loginRedirect = array('admin' => true, 'controller' => 'users', 'action' => 'index');
        } else { 
            $this->Auth->userScope = array('User.is_admin' => 'N');
            $this->Auth->loginAction = array('admin' => false, 'controller' => 'users', 'action' => 'login');
            $this->Auth->loginRedirect = array('admin' => false, 'controller' => 'users', 'action' => 'index');
        }
        $this->Auth->loginError = "Access denied....";
        $this->Auth->authError = "Sorry, you are lacking access.";
        $this->Auth->autoRedirect = false;
        //   $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'profile');

    }

    function login() {
        $this->layout = "login";
        if (!empty($this->data)) {
            if ($this->Auth->user()) {
                $this->Session->setFlash(__('You are logged in!', true), 'information');
                $this->User->id = $this->Auth->user('id');
                $this->User->saveField('last_login', date('Y-m-d H:i:s'));
                if (!empty($this->data['User']['remember_me'])) {
                    $cookie = array();
                    $cookie['email'] = $this->data['User']['email'];
                    $cookie['password'] = $this->data['User']['password'];
                    $this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
                    unset($this->data['User']['remember_me']);
                }
                $this->redirect($this->Auth->redirect());
            } else {
                $this->Session->setFlash(__('Either username or password was wrong!', true), 'error');
            }
        }


        if (empty($this->data)) {
            $cookie = $this->Cookie->read('Auth.User');
            if (!is_null($cookie)) {
                if ($this->Auth->login($cookie)) {
                    //  Clear auth message, just in case we use it.
                    $this->Session->delete('Message.auth');
                    $this->redirect($this->Auth->redirect());
                }
            }
        }
    }

    function myprofile() {
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $this->Auth->User('id'));
            $this->data['User']['password'] = "";
        }
    }

    function logout() {
        $this->Session->setFlash('Good-Bye', 'success');
        //$this->Cookie->delete('Auth.User');
        $this->redirect($this->Auth->logout());
    }

    // ################### Admin Function Start here ###############################    

    function admin_login() {
        $this->layout = "login";
        if (!empty($this->data)) {
            if ($this->Auth->user()) {
                $this->Session->setFlash(__('You are logged in!', true), 'information');
                $this->User->id = $this->Auth->user('id');
                $this->User->saveField('last_login', date('Y-m-d H:i:s'));
                if (!empty($this->data['User']['remember_me'])) {
                    $cookie = array();
                    $cookie['email'] = $this->data['User']['email'];
                    $cookie['password'] = $this->data['User']['password'];
                    $this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
                    unset($this->data['User']['remember_me']);
                }
                $this->redirect($this->Auth->redirect());
            } else {
                $this->Session->setFlash(__('Either username or password was wrong!', true), 'error');
            }
        }


        if (empty($this->data)) {
            $cookie = $this->Cookie->read('Auth.User');
            if (!is_null($cookie)) {
                if ($this->Auth->login($cookie)) {
                    //  Clear auth message, just in case we use it.
                    $this->Session->delete('Message.auth');
                    $this->redirect($this->Auth->redirect());
                }
            }
        }
    }

    function admin_logout() {
        $this->Session->setFlash('Good-Bye', 'success');
        //$this->Cookie->delete('Auth.User');
        $this->redirect($this->Auth->logout());
    }

    function admin_index() {
        $this->User->recursive = 0;
                 
        $this->paginate = array('limit'=>$this->paginationLimit, 'conditions' => array('User.is_admin'=>'N'), "order" => array("user.created" => 'DESC'));
        
        $this->set('users', $this->paginate());
    }

    function admin_view($id = null) {
        
        if (!$id) {
            $this->Session->setFlash(__('Invalid User.', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    function admin_add() {
        if (!empty($this->data)) { 
           
            $this->data['User']['is_admin']='N';
             $this->User->create();
            // $this->User->save($this->data);
            if ($this->User->save($this->data)) {
                $this->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
                $this->Session->setFlash(__('The User has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
            }
        }
    }

    function admin_edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('The User has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
    }
    function admin_editprofile() {
        $this->set('page_title', 'My profile');
        $id=$this->Auth->user('id');
        if (!$id && empty($this->data)) {
            $this->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('The User has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $this->Auth->user('id'));
        }
    }
    function admin_changepassword(){
         $this->set('page_title', 'Change Password');
         
          if (!empty($this->data)) {
             //validate the old password
                $userData  = $this->User->read(null, $this->Auth->user('id'));
                $validateerror =0;
                if($this->Auth->password($this->data['User']['old_passowrd'])!=$userData['User']['password']){
                    $validateerror ++;
                    $errormessage = "Old password was wrong";

                }
                  if($validateerror>0){
                      $this->Session->setFlash(__($errormessage, true),'error');
                      $this->redirect(array('action' => 'admin_changepassword'));
                  }
              
               
               $this->data['User']['passowrd'] = $this->Auth->password($this->data['User']['new_passowrd']);
               $this->User->id = $this->Auth->user('id');
            if ($this->User->saveField('password',$this->data['User']['passowrd'])){
                  $paramArr = array('newpassword'=>$this->data['User']['new_passowrd'],'email'=>$userData['User']['email']);
                   $this->sendMail($userData['User']['email'], 'Password changed information', "changepassword", "imaanand@gmail.com", $paramArr);

                $this->Session->setFlash(__('The password has been updated', true),'success');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The Passowrd could not be updated. Please, try again.', true),'error');
            }
        }
             
    }
    function admin_delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for User', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->User->delete($id)) {
            $this->Session->setFlash(__('User deleted', true));
            $this->redirect(array('action' => 'index'));
        }
    }
     function generateRandomPassword() {

        $chars = "abcdefghijkmnopqrstuvwxyz023456789";

        srand((double) microtime() * 1000000);

        $i = 0;

        $pass = '';



        while ($i <= 7) {

            $num = rand() % 33;

            $tmp = substr($chars, $num, 1);

            $pass = $pass . $tmp;

            $i++;
        }

        return $pass;
    }
}

// ################### Admin Function End here ###############################
?>